package commodityAdd;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.award.jdbc.dao.JdbcDao;
import com.award.model.Commodity;

public class commodityAdd extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Commodity commodity = new Commodity();
		String openTime = null;
		String path = this.getServletContext().getRealPath("/");
		String userImgURL = null;
		if (ServletFileUpload.isMultipartContent(request)) {

			try {
				// 1. 创建DiskFileItemFactory对象，设置缓冲区大小和临时文件目录
				DiskFileItemFactory factory = new DiskFileItemFactory();
				// System.out.println(System.getProperty("java.io.tmpdir"));//默认临时文件夹

				// 2. 创建ServletFileUpload对象，并设置上传文件的大小限制。
				ServletFileUpload sfu = new ServletFileUpload(factory);
				// 限制图片大小为2Mb
				sfu.setSizeMax(10 * 1024 * 1024);// 以byte为单位 不能超过10M 1024byte =
				// 1kb 1024kb=1M 1024M = 1G
				sfu.setHeaderEncoding("utf-8");

				// 3.
				// 调用ServletFileUpload.parseRequest方法解析request对象，得到一个保存了所有上传内容的List对象。
				List<FileItem> fileItemList = sfu.parseRequest(request);
				Iterator<FileItem> fileItems = fileItemList.iterator();

				// 4. 遍历list，每迭代一个FileItem对象，调用其isFormField方法判断是否是上传文件
				while (fileItems.hasNext()) {
					FileItem fileItem = fileItems.next();
					// 普通表单元素
					if (fileItem.isFormField()) {
						String name = fileItem.getFieldName();// name属性值
						String value = fileItem.getString("utf-8");// name对应的value值
						switch (name) {
						case "commodityName":
							commodity.setCommodityName(value);
							break;
						case "commodityPrice":
							commodity.setPrice(Float.parseFloat(value));
							break;
						case "user_date":
							openTime = value.replaceAll("T", " ") + ":00";
							SimpleDateFormat formatter = new SimpleDateFormat(
									"yyyy-MM-dd HH:mm:ss");
							Date openTime1 = formatter.parse(openTime);
							commodity.setOpenTime(openTime1);
							break;
						case "totalNum":
							commodity.setTotal(Integer.parseInt(value));
							break;
						}

						System.out.println(name + " = " + value);
					}
					// <input type="file">的上传文件的元素
					else {
						String fileName = fileItem.getName();// 文件名称
						System.out.println("原文件名：" + fileName);// Koala.jpg

						String suffix = fileName.substring(fileName
								.lastIndexOf('.'));
						System.out.println("扩展名：" + suffix);// .jpg

						// 新文件名（唯一）
						int length = fileName.indexOf('.');
						int hz = (int) (Math.random() * 100000);
						UUID HN = UUID.randomUUID();
						String headName = HN.toString();
						headName = headName.substring(0, headName.indexOf('-'));
						String newFileName = headName + String.valueOf(hz)
								+ suffix;
						System.out.println("新文件名：" + newFileName);// image\1478509873038.jpg
						userImgURL = path + "/images/commodityImg/"
								+ newFileName;
						// 5. 调用FileItem的write()方法，写入文件
						File file = new File(userImgURL);
						System.out.println(file.getAbsolutePath());
						fileItem.write(file);

						// 6. 调用FileItem的delete()方法，删除临时文件
						fileItem.delete();

						/*
						 * 存储到数据库时注意 1.保存源文件名称 Koala.jpg 2.保存相对路径
						 * image/1478509873038.jpg
						 */
						commodity.setImgURL("./images/commodityImg/"
								+ newFileName);

					}
				}
				commodity.setAward(-1);
				commodity.setAwardUserID(0);
				commodity.setSelectPeopleNum(0);
				JdbcDao jdbcDao = new JdbcDao();
				jdbcDao.insertCommodity(commodity);
				response.sendRedirect(request.getContextPath()
						+ "/jsp/manager/addSuccessful.jsp?type=commodity");
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
}
